<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { listCourses, addCourse, updateCourse, removeCourse } from '../services/courseApi'
import logo from '../assets/logo.svg'
import { Edit, Delete } from '@element-plus/icons-vue'


// 搜索表单
const qName = ref('')
const qCategory = ref('')
const qAudience = ref('')

// 列表与分页
const list = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const lastAction = ref('init')

// 轻量提示（Toast）
const toast = reactive({ show: false, type: 'info', text: '' })
function notify(text, type = 'info') {
  toast.text = text
  toast.type = type
  toast.show = true
  setTimeout(() => { toast.show = false }, 2000)
}

async function loadList() {
  loading.value = true
  try {
    const { list: rows, total: t } = await listCourses({
      page: page.value,
      pageSize: pageSize.value,
      name: qName.value,
      category: qCategory.value,
      audience: qAudience.value
    })
    list.value = rows || []
    total.value = t || rows?.length || 0
    if (total.value === 0 && lastAction.value !== 'page') {
      notify('暂无数据', 'info')
    }
  } catch (e) {
    notify(e.message || '不好意思，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

function search(silent = false) {
  page.value = 1
  lastAction.value = 'search'
  if (!silent) notify('已应用筛选条件', 'info')
  loadList()
}

function clear() {
  qName.value = ''
  qCategory.value = ''
  qAudience.value = ''
  page.value = 1
  lastAction.value = 'clear'
  notify('已重置筛选条件', 'info')
  loadList()
}

// 添加/编辑弹窗
const showAdd = ref(false)
const showEdit = ref(false)
const showDelete = ref(false)

const form = reactive({ id: null, category: '', name: '', price: '', audience: '', intro: '' })
const currentId = ref(null)

function openAdd() {
  Object.assign(form, { id: null, category: '', name: '', price: '', audience: '', intro: '' })
  showAdd.value = true
}
async function confirmAdd() {
  try {
    await addCourse({
      category: form.category,
      name: form.name,
      price: Number(form.price) || 0,
      audience: form.audience,
      intro: form.intro
    })
    showAdd.value = false
    notify('添加成功', 'success')
    lastAction.value = 'add'
    loadList()
  } catch (e) { notify(e.message || '不好意思，请稍后重试', 'error') }
}

function openEdit(row) {
  Object.assign(form, row)
  currentId.value = row.id
  showEdit.value = true
}
async function confirmEdit() {
  try {
    await updateCourse(currentId.value, {
      category: form.category,
      name: form.name,
      price: Number(form.price) || 0,
      audience: form.audience,
      intro: form.intro
    })
    showEdit.value = false
    notify('修改成功', 'success')
    lastAction.value = 'edit'
    loadList()
  } catch (e) { notify(e.message || '不好意思，请稍后重试', 'error') }
}

function openDelete(row) {
  currentId.value = row.id
  Object.assign(form, row)
  showDelete.value = true
}
async function confirmDelete() {
  try {
    await removeCourse(currentId.value)
    showDelete.value = false
    if (list.value.length === 1 && page.value > 1) page.value -= 1
    notify('删除成功', 'success')
    lastAction.value = 'delete'
    loadList()
  } catch (e) { notify(e.message || '不好意思，请稍后重试', 'error') }
}

// 客户端渲染序号
const rowStartIndex = computed(() => (page.value - 1) * pageSize.value)

// 初始化加载
onMounted(loadList)

// 分页变化提示与加载
watch(page, (nv, ov) => {
  if (nv !== ov) {
    lastAction.value = 'page'
    notify(`已跳转到第 ${nv} 页`, 'info')
    loadList()
  }
})

// 每页数量变化提示与加载
watch(pageSize, (nv, ov) => {
  if (nv !== ov) {
    lastAction.value = 'pageSize'
    page.value = 1
    notify(`每页显示 ${nv} 条`, 'info')
    loadList()
  }
})
// 用户信息与注销逻辑已迁移至主布局（MainLayout），本页面移除重复代码。

</script>

<template>
  <div class="container">
    <div class="toolbar">
      <div class="filter-row">
        <div class="field">
          <span class="label">课程名称：</span>
          <input v-model="qName" placeholder="请输入" />
        </div>
        <div class="field">
          <span class="label">课程学科：</span>
          <select v-model="qCategory">
            <option value="">请选择</option>
            <option value="AI智能应用开发(Java)">AI智能应用开发(Java)</option>
            <option value="AI大模型开发(Python)">AI大模型开发(Python)</option>
            <option value="AI鸿蒙开发">AI鸿蒙开发</option>
            <option value="AI大数据">AI大数据</option>
            <option value="AI嵌入式">AI嵌入式</option>
            <option value="AI测试">AI测试</option>
            <option value="AI运维">AI运维</option>
          </select>
        </div>
        <div class="field">
          <span class="label">适用人群：</span>
          <select v-model="qAudience">
            <option value="">请选择</option>
            <option value="小白学员">小白学员</option>
            <option value="中级程序员">中级程序员</option>
            <option value="高级程序员">高级程序员</option>
          </select>
        </div>
        <div class="actions">
          <button class="btn" @click="search"><span class="icon">🔍</span>搜索</button>
          <button class="btn btn-secondary" @click="clear"><span class="icon">♻️</span>重置</button>
        </div>
      </div>
      <div class="toolbar-divider"></div>
      <div class="action-row">
        <button class="btn btn-primary" @click="openAdd">+ 添加课程</button>
      </div>
    </div>

    <div class="table-card">
      <table>
        <tr>
          <th>序号</th>
          <th>课程学科</th>
          <th>课程名称</th>
          <th>价格（元）</th>
          <th>适用人群</th>
          <th>课程介绍</th>
          <th>最后更新时间</th>
          <th>操作</th>
        </tr>
        <tr v-if="loading">
          <td colspan="8" class="loading">正在加载...</td>
        </tr>
        <tr v-for="(c, i) in list" :key="c.id">
          <td>{{ rowStartIndex + i + 1 }}</td>
          <td>{{ c.category }}</td>
          <td>{{ c.name }}</td>
          <td>{{ c.price }}</td>
          <td>{{ c.audience }}</td>
          <td class="intro">{{ c.intro }}</td>
          <td>{{ c.updatedAt }}</td>
          <td>
            <el-button size="small" type="primary" @click="openEdit(c)"><el-icon><Edit/></el-icon>修改</el-button>
            <el-button size="small" type="danger" @click="openDelete(c)"><el-icon><Delete/></el-icon>删除</el-button>
          </td>
        </tr>
        <tr v-if="!loading && list.length === 0">
          <td colspan="8" class="empty">暂无数据</td>
        </tr>
      </table>
    </div>

    <div class="pagination">
      <div class="left">共 {{ total }} 条记录 第 {{ page }} / {{ Math.max(1, Math.ceil(total / pageSize)) }} 页</div>
      <div class="pages">
        <button class="page" :disabled="page === 1" @click="page = 1">«</button>
        <button class="page" :disabled="page === 1" @click="page--">‹</button>
        <button v-for="p in Math.min(Math.ceil(total / pageSize), 9)" :key="p" class="page" :class="{ active: page === p }" @click="page = p">{{ p }}</button>
        <button class="page" :disabled="page === Math.ceil(total / pageSize)" @click="page++">›</button>
        <button class="page" :disabled="page === Math.ceil(total / pageSize)" @click="page = Math.ceil(total / pageSize)">»</button>
      </div>
      <div class="right">
        <select v-model.number="pageSize" @change="page = 1">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 添加课程弹窗 -->
    <div v-if="showAdd" class="modal">
      <div class="dialog">
        <div class="dialog-header">添加课程</div>
        <div class="dialog-body">
          <div class="form-grid">
            <label>课程学科</label>
            <select v-model="form.category">
              <option value="AI智能应用开发(Java)">AI智能应用开发(Java)</option>
              <option value="AI大模型开发(Python)">AI大模型开发(Python)</option>
              <option value="AI鸿蒙开发">AI鸿蒙开发</option>
              <option value="AI大数据">AI大数据</option>
              <option value="AI嵌入式">AI嵌入式</option>
              <option value="AI测试">AI测试</option>
              <option value="AI运维">AI运维</option>
            </select>
            <label>课程名称</label>
            <input v-model="form.name" placeholder="请输入课程名称" />
            <label>价格（元）</label>
            <input v-model="form.price" type="number" min="0" placeholder="请输入价格" />
            <label>适用人群</label>
            <select v-model="form.audience">
              <option value="小白学员">小白学员</option>
              <option value="中级程序员">中级程序员</option>
              <option value="高级程序员">高级程序员</option>
            </select>
            <label>课程介绍</label>
            <textarea v-model="form.intro" rows="3" placeholder="请输入课程介绍"></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="showAdd = false">取消</button>
          <button class="btn" @click="confirmAdd">确定</button>
        </div>
      </div>
    </div>

    <!-- 编辑课程弹窗 -->
    <div v-if="showEdit" class="modal">
      <div class="dialog">
        <div class="dialog-header">修改课程</div>
        <div class="dialog-body">
          <div class="form-grid">
            <label>课程学科</label>
            <select v-model="form.category">
              <option value="AI智能应用开发(Java)">AI智能应用开发(Java)</option>
              <option value="AI大模型开发(Python)">AI大模型开发(Python)</option>
              <option value="AI鸿蒙开发">AI鸿蒙开发</option>
              <option value="AI大数据">AI大数据</option>
              <option value="AI嵌入式">AI嵌入式</option>
              <option value="AI测试">AI测试</option>
              <option value="AI运维">AI运维</option>
            </select>
            <label>课程名称</label>
            <input v-model="form.name" />
            <label>价格（元）</label>
            <input v-model="form.price" type="number" min="0" />
            <label>适用人群</label>
            <select v-model="form.audience">
              <option value="小白学员">小白学员</option>
              <option value="中级程序员">中级程序员</option>
              <option value="高级程序员">高级程序员</option>
            </select>
            <label>课程介绍</label>
            <textarea v-model="form.intro" rows="3"></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="showEdit = false">取消</button>
          <button class="btn" @click="confirmEdit">保存</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDelete" class="modal">
      <div class="dialog small">
        <div class="dialog-header">确认删除</div>
        <div class="dialog-body">
          是否删除课程“{{ form.name }}”？此操作不可恢复。
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="showDelete = false">取消</button>
          <el-button type="danger" @click="confirmDelete"><el-icon><Delete/></el-icon>删除</el-button>
        </div>
      </div>
    </div>
    

    

    <!-- 轻量提示 -->
    <div v-if="toast.show" class="toast" :class="toast.type">{{ toast.text }}</div>
  </div>
</template>


<style scoped>
.container { width: 100%; margin: 0; padding: 0 16px 16px 16px; position: relative; }
.toolbar { display:flex; flex-direction:column; gap:12px; }
.filter-row { display:flex; align-items:center; gap:12px; flex-wrap:nowrap; }
.action-row { display:flex; align-items:center; gap:10px; }
.toolbar-divider { height:1px; background:#e5e7eb; }
.toolbar .spacer { width: 8px; }
.field { display: flex; align-items: center; gap: 8px; }
.label { color: #374151; }
.actions { margin-left: auto; display: flex; gap: 10px; }

.table-card { margin-top: 14px; background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; box-shadow: 0 6px 16px rgba(0,0,0,0.06); overflow-x: auto; min-height: 520px; }
.table-card table { width: 100%; border-collapse: collapse; }
.table-card th, .table-card td { border: 1px solid #e5e7eb; line-height: 52px; text-align: center; }
.table-card th { background: #f7f7f8; color: #374151; font-weight: 600; }
.table-card .intro { max-width: 360px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.table-card .loading, .table-card .empty { color: #6b7280; height: 60px; }

.pagination { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; }
.pagination .left { color: #666; }
.pagination .pages { display: flex; gap: 6px; }
.page { padding: 4px 10px; border: 1px solid #e5e7eb; border-radius: 6px; background: #fff; cursor: pointer; }
.page.active { background: #08dcf3; border-color: #08dcf3; color: #0f172a; }
.page:disabled { opacity: 0.5; cursor: not-allowed; }
.pagination .right select { padding: 6px 8px; border: 1px solid #d1d5db; border-radius: 6px; }

input, select, textarea { padding: 8px 10px; border: 1px solid #d1d5db; border-radius: 6px; background: #fff; min-width: 160px; }

.btn { background: #08dcf3; color: #0f172a; padding: 8px 20px; border-radius: 8px; border: 1px solid #08dcf3; cursor: pointer; }
.btn:hover { opacity: 0.9; }
.btn-primary { background: #1677ff; border-color: #1677ff; color: #fff; }
.btn-secondary { background: #fff; border-color: #cbd5e1; color: #0f172a; }
.btn.danger { background: #ff4d4f; border-color: #ff4d4f; color: #fff; }
.link{ background:none; border:none; color:#1677ff; cursor:pointer; }
.link.danger{ color:#ff4d4f; }

/* 弹窗 */
.modal { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display: grid; place-items: center; z-index: 1000; }
.dialog { background: #fff; border-radius: 12px; width: 720px; max-width: calc(100% - 48px); box-shadow: 0 10px 24px rgba(0,0,0,0.15); }
.dialog.small { width: 420px; }
.dialog-header { padding: 14px 18px; font-weight: 600; border-bottom: 1px solid #eee; }
.dialog-body { padding: 16px 18px; color: #333; }
.dialog-footer { padding: 12px 18px; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #eee; }
.form-grid { display: grid; grid-template-columns: 120px 1fr; gap: 12px; align-items: center; }
.form-grid textarea { grid-column: 1 / -1; }
.toast { position: fixed; top: 18px; left: 50%; transform: translateX(-50%); padding: 10px 14px; border-radius: 8px; color: #0f172a; box-shadow: 0 8px 20px rgba(0,0,0,0.12); z-index: 2000; background: #fff; border: 1px solid #e5e7eb; }
.toast.success { background: #e6fffb; border-color: #b5f5ec; }
.toast.error { background: #fff1f0; border-color: #ffccc7; }
.toast.info { background: #f0f9ff; border-color: #bae6fd; }

</style>